﻿using Dlpad.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client;
using Microsoft.IdentityModel.Tokens;
using Model;
using Model.Options;
using StackExchange.Redis;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

//加载环境变量
builder.Configuration.AddEnvironmentVariables();

// 验证密钥是否加载
var jwtKey = builder.Configuration["Jwt:Key"];
if (string.IsNullOrEmpty(jwtKey))
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("错误：Jwt:Key 未配置！需要设置环境变量");
    Environment.Exit(1);
}
Console.WriteLine($"Jwt:Key 已加载，长度: {jwtKey.Length}");

// 1. 读取配置并注册选项类
builder.Services.Configure<CacheOptions>(builder.Configuration.GetSection("Cache"));

// 添加CORS配置
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// 注册服务
builder.Services.AddScoped<ICacheService, CacheService>();
builder.Services.AddScoped<IDictTypeService, DictTypeService>();
builder.Services.AddScoped<IDictDataService, DictDataService>();

// 注册认证服务
builder.Services.AddScoped<IAuthService, AuthService>();

//注册缓存初始化服务
builder.Services.AddHostedService<DictCacheInitializerHostedService>();



//JWT认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,// 验证iss声明
            ValidateAudience = true,// 验证aud声明
            ValidateLifetime = true,// 验证exp声明
            ValidateIssuerSigningKey = true,// 验证签名
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new  SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });


builder.Services.AddControllers();
// 配置数据库上下文
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 配置Redis - 先注册 IConnectionMultiplexer
builder.Services.AddSingleton<IConnectionMultiplexer>(provider =>
{
    var connectionString = "localhost:6379,password=123,allowAdmin=true,abortConnect=false,connectTimeout=10000,syncTimeout=10000,asyncTimeout=10000,keepAlive=30,connectRetry=5";
    Console.WriteLine($"[REDIS-CONFIG] 创建 IConnectionMultiplexer: {connectionString}");
    return ConnectionMultiplexer.Connect(connectionString);
});

// 然后配置 IDistributedCache
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379,password=123,allowAdmin=true,abortConnect=false,connectTimeout=10000,syncTimeout=10000";
    options.InstanceName = "";
    Console.WriteLine($"[REDIS-CONFIG] Redis 配置完成");
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors("AllowAll");

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

// 手动缓存预热端点
app.MapPost("/api/dict/cache/warmup", async (IServiceProvider serviceProvider) =>
{
    try
    {
        using var scope = serviceProvider.CreateScope();
        var dictTypeService = scope.ServiceProvider.GetRequiredService<IDictTypeService>();
        var dictDataService = scope.ServiceProvider.GetRequiredService<IDictDataService>();
        var cacheService = scope.ServiceProvider.GetRequiredService<ICacheService>();

        // 清除现有缓存
        await cacheService.ClearAllDictCacheAsync();

        // 重新加载所有字典类型
        var dictTypes = await dictTypeService.GetAllDictTypesFromDbAsync();

        // 预加载每个字典类型的数据
        int totalDataCount = 0;
        foreach (var dictType in dictTypes)
        {
            var data = await dictDataService.GetDictDataByTypeAsync(dictType.DictType);
            totalDataCount += data.Count;
        }

        return Results.Ok(new
        {
            message = "缓存预热完成",
            dictTypesCount = dictTypes.Count,
            totalDataCount = totalDataCount,
            timestamp = DateTime.Now
        });
    }
    catch (Exception ex)
    {
        return Results.Problem($"缓存预热失败: {ex.Message}");
    }
});

app.Run();
